﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Transactions;

namespace aspnet2.Manager
    {
    public partial class ManagerProfile : System.Web.UI.Page
        {
        DataClasses1DataContext db = new DataClasses1DataContext();
        public void GridProductBind()
            {
            var _gridproduct = from _product in db.Product
                               where _product.Type<3
                               select new
                               {
                                   _product.ID
                                   ,
                                   _product.Name
                                   ,
                                   _product.CurrentPrice
                                   ,
                                   _product.Unit
                                   ,
                                   _product.ImgURL,
                                   // _product.Warranty.WarrantyContent

                               };

            GridProduct.DataSource = _gridproduct;
            GridProduct.DataBind();

            }

        protected void Page_Load(object sender, EventArgs e)
            {

            try
                {
                if (!HttpContext.Current.User.IsInRole("Manager")) { Response.Redirect(FormsAuthentication.LoginUrl); return; }
                if (!this.IsPostBack) 
                    { 
                    this.GridProductBind();
                    this.ErrorInfo.Text = null; 
                    }
                
                }
            catch (Exception ex)
                {
                this.ErrorInfo.Text = ex.Message;
                }
            }
        /// <summary>
        /// 添加进product,再添加price,再添加时间;再根据type添加精解product(machine啊，ink啊。。。
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void AddProduct_Click(object sender, EventArgs e)
            {

            try
                {

                if (this.ProductName.Text != null && this.ProductPrice.Text != null)
                    {
                    using (TransactionScope ts = new TransactionScope())
                        {
                        ///添加product与price
                        DataClasses1DataContext db = new DataClasses1DataContext();
                        var _productidquery = from _producttemp in db.Product
                                              where _producttemp.Name == this.ProductName.Text
                                              select _producttemp.ID;
                        if ((_productidquery.ToArray()).Length > 0) throw new Exception("产品已添加过！");
                        Product _product = new Product();
                        _product.Name = this.ProductName.Text;
                        _product.CurrentPrice = decimal.Parse(this.ProductPrice.Text);
                        _product.Type = Int32.Parse(this.DropDownList1.SelectedValue);
                        db.Product.InsertOnSubmit(_product);

                        ProductPrice _productpricetemp = new ProductPrice();
                        _productpricetemp.Value = decimal.Parse(this.ProductPrice.Text);

                        var _productpricequery = from _productprice in db.ProductPrice
                                                 where _productprice.Value == _productpricetemp.Value
                                                 select _productprice;

                        if (_productpricequery.ToArray().Length == 0)
                            {

                            db.ProductPrice.InsertOnSubmit(_productpricetemp);

                            }
                        db.SubmitChanges();
                        ///添加productpricecosthitory
                        ProductPriceCostHistory _productpricecosthistory = new ProductPriceCostHistory();

                        _productpricecosthistory.IsCostType = false;
                        _productpricecosthistory.BidingTime = DateTime.Now;

                        var _productpriceidquery = from _productpriceidtemp in db.ProductPrice
                                                   where _productpriceidtemp.Value == decimal.Parse(this.ProductPrice.Text)
                                                   select _productpriceidtemp.PriceID;
                        #region 添加prodcutcosthistory
                        foreach (var _productidtemp in _productidquery)
                            {

                            _productpricecosthistory.ProductID = _productidtemp;

                            break;

                            }
                        foreach (var a in _productpriceidquery)
                            {
                            _productpricecosthistory.PriceID = a;
                            break;
                            }
                        #endregion
                        db.ProductPriceCostHistory.InsertOnSubmit(_productpricecosthistory);
                        db.SubmitChanges();

                        foreach (var _productidtemp in _productidquery)
                            {

                            switch (Int32.Parse(DropDownList1.SelectedValue))
                                {
                                case 0:
                                    Machine _machine = new Machine();
                                    _machine.ID = _productidtemp;
                                    db.Machine.InsertOnSubmit(_machine);
                                    break;
                                case 1:
                                    Ink _ink = new Ink();
                                    _ink.TypeID = _productidtemp;
                                    db.Ink.InsertOnSubmit(_ink);

                                    break;
                                case 2:
                                    Peijian _peijian = new Peijian();
                                    _peijian.ID = _productidtemp;
                                    db.Peijian.InsertOnSubmit(_peijian);
                                    break;
                                case 3:
                                    break;
                                }

                            break;

                            }
                        db.SubmitChanges();
                        this.GridProductBind();
                        ts.Complete();

                        }
                    }
                }
            catch (Exception ex)
                {
                this.ErrorInfo.Text = ex.Message;

                
                }
            }

        protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
            {

            try
                {
                this.GridProduct.EditIndex = e.NewEditIndex;
                GridProductBind();
                }
            catch (Exception ex)
                {

                this.ErrorInfo.Text = ex.Message;
                }
            }

        protected void GridProduct_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
            {
            try
                {
                this.GridProduct.EditIndex = -1;
                GridProductBind();
                }
            catch (Exception ex)
                {

                this.ErrorInfo.Text = ex.Message;
                }
            }

        protected void GridProduct_RowUpdating(object sender, GridViewUpdateEventArgs e)
            {
            try
                {
                int _productidtemp = Int32.Parse(((TextBox)this.GridProduct.Rows[e.RowIndex].Cells[1].Controls[0]).Text);
                var _productquery = from _product in db.Product
                                    where _product.ID == _productidtemp
                                    select _product;
                foreach (var _producttemp in _productquery)
                    {
                    _producttemp.Name = ((TextBox)this.GridProduct.Rows[e.RowIndex].Cells[2].Controls[0]).Text;
                    _producttemp.CurrentPrice = decimal.Parse(((TextBox)this.GridProduct.Rows[e.RowIndex].Cells[3].Controls[0]).Text);
                    _producttemp.Unit = ((TextBox)this.GridProduct.Rows[e.RowIndex].Cells[4].Controls[0]).Text; ;
                    _producttemp.ImgURL = ((TextBox)this.GridProduct.Rows[e.RowIndex].Cells[5].Controls[0]).Text;

                    db.SubmitChanges();

                    this.GridProduct.EditIndex = -1;
                    this.GridProductBind();


                    break;
                    }
                }
            catch (Exception ex)
                {

                this.ErrorInfo.Text = ex.Message;
                }
            }

        protected void GridProduct_SelectedIndexChanged(object sender, EventArgs e)
            {

            }

        protected void GridProduct_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
            {
            try
                {
                int _productidtemp = Int32.Parse(this.GridProduct.DataKeys[e.NewSelectedIndex].Value.ToString());
                var _productquery = (from _product in db.Product
                                     where _product.ID == _productidtemp
                                     select _product).ToArray();
                switch (_productquery[0].Type)
                    {
                    case 0:
                        this.DetailProduct.DataSource = from _machine in db.Machine
                                                        where _machine.ID == _productidtemp
                                                        select _machine;
                        this.DetailProduct.DataBind();

                        break;
                    case 1:
                        this.DetailProduct.DataSource = from _ink in db.Ink
                                                        where _ink.TypeID == _productidtemp
                                                        select _ink;
                        this.DetailProduct.DataBind();
                        break;
                    case 2:
                        this.DetailProduct.DataSource = from _peijian in db.Peijian
                                                        where _peijian.ID == _productidtemp
                                                        select _peijian;
                        this.DetailProduct.DataBind();
                        break;
                    }
                }
            catch (Exception ex)
                {

                this.ErrorInfo.Text = ex.Message;
                }


            }

        protected void GridProduct_RowDeleting(object sender, GridViewDeleteEventArgs e)
            {
            try
                {
                var _productquery = from _product in db.Product
                                    where _product.ID == Int32.Parse(this.GridProduct.Rows[e.RowIndex].Cells[1].Text)
                                    select _product;
                db.Product.DeleteAllOnSubmit(_productquery);
                db.SubmitChanges();
                this.GridProductBind();
                }
            catch (Exception ex) 
                {

                this.ErrorInfo.Text = ex.Message;
                }
            }

        protected void GridProduct_RowUpdated(object sender, GridViewUpdatedEventArgs e)
            {


            }

        protected void DetailProduct_SelectedIndexChanged(object sender, EventArgs e)
            {

            }

        protected void DetailProduct_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
            {


            }

        protected void DetailProduct_RowEditing(object sender, GridViewEditEventArgs e)
            {
            try
                {
                this.DetailProduct.EditIndex = e.NewEditIndex;

                int _productidtemp = Int32.Parse(this.GridProduct.DataKeys[e.NewEditIndex].Value.ToString());
                var _productquery = (from _product in db.Product
                                     where _product.ID == _productidtemp
                                     select _product).ToArray();
                switch (_productquery[0].Type)
                    {
                    case 0:
                        this.DetailProduct.DataSource = from _machine in db.Machine
                                                        where _machine.ID == _productidtemp
                                                        select _machine;
                        this.DetailProduct.DataBind();

                        break;
                    case 1:
                        this.DetailProduct.DataSource = from _ink in db.Ink
                                                        where _ink.TypeID == _productidtemp
                                                        select _ink;
                        this.DetailProduct.DataBind();
                        break;
                    case 2:
                        this.DetailProduct.DataSource = from _peijian in db.Peijian
                                                        where _peijian.ID == _productidtemp
                                                        select _peijian;
                        this.DetailProduct.DataBind();
                        break;
                    }
                }
            catch (Exception ex)
                {

                this.ErrorInfo.Text = ex.Message;
                }

            }

        protected void DetailProduct_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
            {
            try
                {
                this.DetailProduct.EditIndex = -1;
                int _productidtemp = Int32.Parse(this.GridProduct.DataKeys[e.RowIndex].Value.ToString());
                var _productquery = (from _product in db.Product
                                     where _product.ID == _productidtemp
                                     select _product).ToArray();
                switch (_productquery[0].Type)
                    {
                    case 0:
                        this.DetailProduct.DataSource = from _machine in db.Machine
                                                        where _machine.ID == _productidtemp
                                                        select _machine;
                        this.DetailProduct.DataBind();

                        break;
                    case 1:
                        this.DetailProduct.DataSource = from _ink in db.Ink
                                                        where _ink.TypeID == _productidtemp
                                                        select _ink;
                        this.DetailProduct.DataBind();
                        break;
                    case 2:
                        this.DetailProduct.DataSource = from _peijian in db.Peijian
                                                        where _peijian.ID == _productidtemp
                                                        select _peijian;
                        this.DetailProduct.DataBind();
                        break;
                    }

                }
            catch (Exception ex) 
                {

                this.ErrorInfo.Text = ex.Message;
                }
            }

        protected void DetailProduct_RowUpdating(object sender, GridViewUpdateEventArgs e)
            {

            try
                {
                int _productidtemp = Int32.Parse(this.GridProduct.DataKeys[e.RowIndex].Value.ToString());
                var _productquery = (from _product in db.Product
                                     where _product.ID == _productidtemp
                                     select _product).ToArray();
                switch (_productquery[0].Type)
                    {
                    case 0:
                        var machine = from _machine in db.Machine
                                      where _machine.ID == _productidtemp
                                      select _machine;
                        this.DetailProduct.DataSource = machine;

                        this.DetailProduct.DataBind();

                        break;
                    case 1:
                        this.DetailProduct.DataSource = from _ink in db.Ink
                                                        where _ink.TypeID == _productidtemp
                                                        select _ink;
                        this.DetailProduct.DataBind();
                        break;
                    case 2:
                        this.DetailProduct.DataSource = from _peijian in db.Peijian
                                                        where _peijian.ID == _productidtemp
                                                        select _peijian;
                        this.DetailProduct.DataBind();
                        break;
                    }
                }
            catch (Exception ex)
                {

                this.ErrorInfo.Text = ex.Message;
                }
            }

        protected void Button1_Click(object sender, EventArgs e)
            {

            try
                {

                int RowIndex = ((sender as Button).NamingContainer as GridViewRow).RowIndex;
                string UserID = ((Int32)this.GridView1.DataKeys[RowIndex].Values["UserID"]).ToString();
                string ProductID = ((Int32)this.GridView1.DataKeys[RowIndex].Values["ProductID"]).ToString();
                DateTime dt = (DateTime)this.GridView1.DataKeys[RowIndex].Values["CallTime"];
                using (TransactionScope ts = new TransactionScope())
                    {
                    ///如果买的是机器，则用户变为钻石用户
                    ///
                    //db = new DataClasses1DataContext();
                    var x = from a in db.Product
                            where a.ID == Int32.Parse(ProductID) && a.Type == 0
                            select a;
                    if (x != null)
                        {
                        var a = db.PrinterUser.Where(c => c.UserID == Int32.Parse(UserID)).Select(c => c).First();
                        a.UserType = 1;
                        a.UserStarDegree = 0;



                        }

                    var query = (from a in db.UserBuyProduct
                                 where a.UserID == Int32.Parse(UserID) && a.ProductID == Int32.Parse(ProductID) && a.CallTime.CompareTo(dt) == 0
                                 select a).First();
                    query.BuyTime = DateTime.Now;
                    db.SubmitChanges();

                    ///积分的增长
                    var b = db.Product.Where(c => c.ID == Int32.Parse(ProductID)).Select(c => c).First();
                    var d = (from a in db.ProductType
                             where a.TypeID == b.Type
                             select a).First();
                    decimal? AddingPoint = b.CurrentPrice * (decimal.Parse(d.Coeffecient.ToString())) * (decimal)(from a in db.UserBuyProduct
                                                                                                                  where a.UserID == Int32.Parse(UserID) && a.ProductID == Int32.Parse(ProductID) && a.CallTime.CompareTo(dt) == 0
                                                                                                                  select a).First().Quantity;
                    var User = db.PrinterUser.Where(c => c.UserID == Int32.Parse(UserID)).Select(c => c).First();

                    User.Point += AddingPoint;
                    db.SubmitChanges();
                    ///用户等级变更
                    var Us = db.PrinterUser.Where(c => c.UserID == Int32.Parse(UserID)).Select(c => c).First();

                    foreach (var temp in (from temp2 in db.UserDegree
                                          where Us.UserStarDegree < temp2.UserStarDegree && temp2.UserType == Us.UserType
                                          select temp2))
                        {
                        if (Us.Point >= temp.Threshold)
                            {
                            Us.UserStarDegree = temp.UserStarDegree;
                            }



                        }



                    db.SubmitChanges();

                    ts.Complete();



                    }
                this.GridView1.DataBind();

                }
            catch (Exception ex)
                {

                this.ErrorInfo.Text = ex.Message;
                }
                

            }

        protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
            {

            }
        //用户购买服务确认
        protected void GridView2_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
            {
            try
                {
                int ServiceID = (int)this.UserBuyService.DataKeys[e.NewSelectedIndex]["ServiceID"];
                int UserID = (int)this.UserBuyService.DataKeys[e.NewSelectedIndex]["UserID"];
                DateTime BuyTime = (DateTime)this.UserBuyService.DataKeys[e.NewSelectedIndex]["BuyTime"];
                var k = from a in db.UserBuyService
                        where a.ServiceID == ServiceID && a.UserID == UserID && a.BuyTime == BuyTime
                        select a;
                if (k.ToArray().Count() > 0)
                    {
                    //服务解决
                    k.First().Solved = true;
                    db.SubmitChanges();
                    this.UserBuyService.DataBind();
                    }
                }
            catch (Exception ex)
                {

                this.ErrorInfo.Text = ex.Message;
                }
            

            }

        protected void UserBuyService_SelectedIndexChanged(object sender, EventArgs e)
            {

            }

        protected void GridView1_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
            {

            try
                {
                string UserID = ((Int32)this.GridView1.DataKeys[e.NewSelectedIndex].Values["UserID"]).ToString();
                string ProductID = ((Int32)this.GridView1.DataKeys[e.NewSelectedIndex].Values["ProductID"]).ToString();
                DateTime dt = (DateTime)this.GridView1.DataKeys[e.NewSelectedIndex].Values["CallTime"];
                using (TransactionScope ts = new TransactionScope())
                    {
                    ///如果买的是机器，则用户变为钻石用户
                    ///
                    //db = new DataClasses1DataContext();
                    var x = from a in db.Product
                            where a.ID == Int32.Parse(ProductID) && a.Type == 0
                            select a;
                    if (x != null)
                        {
                        var a = db.PrinterUser.Where(c => c.UserID == Int32.Parse(UserID)).Select(c => c).First();
                        a.UserType = 1;
                        a.UserStarDegree = 0;



                        }

                    var query = (from a in db.UserBuyProduct
                                 where a.UserID == Int32.Parse(UserID) && a.ProductID == Int32.Parse(ProductID) && a.CallTime.CompareTo(dt) == 0
                                 select a).First();
                    query.BuyTime = DateTime.Now;
                    db.SubmitChanges();

                    ///积分的增长
                    var b = db.Product.Where(c => c.ID == Int32.Parse(ProductID)).Select(c => c).First();
                    var d = (from a in db.ProductType
                             where a.TypeID == b.Type
                             select a).First();
                    decimal? AddingPoint = b.CurrentPrice * (decimal.Parse(d.Coeffecient.ToString())) * (decimal)(from a in db.UserBuyProduct
                                                                                                                  where a.UserID == Int32.Parse(UserID) && a.ProductID == Int32.Parse(ProductID) && a.CallTime.CompareTo(dt) == 0
                                                                                                                  select a).First().Quantity;
                    var User = db.PrinterUser.Where(c => c.UserID == Int32.Parse(UserID)).Select(c => c).First();

                    User.Point += AddingPoint;
                    db.SubmitChanges();
                    ///用户等级变更
                    var Us = db.PrinterUser.Where(c => c.UserID == Int32.Parse(UserID)).Select(c => c).First();

                    foreach (var temp in (from temp2 in db.UserDegree
                                          where Us.UserStarDegree < temp2.UserStarDegree && temp2.UserType == Us.UserType
                                          select temp2))
                        {
                        if (Us.Point >= temp.Threshold)
                            {
                            Us.UserStarDegree = temp.UserStarDegree;
                            }



                        }



                    db.SubmitChanges();

                    ts.Complete();



                    }
                this.GridView1.DataBind();
                }
            catch (Exception ex)
                {

                this.ErrorInfo.Text = ex.Message;
                }

            }

        protected void GridView1_SelectedIndexChanged1(object sender, EventArgs e)
            {

            }

        protected void LinkButton1_Click(object sender, EventArgs e)
            {
            Response.Redirect(FormsAuthentication.DefaultUrl);
            }

        protected void LinkButton2_Click(object sender, EventArgs e)
            {
            Response.Redirect("~/UserProfile.aspx");
            }


        }
    }
